const baseUrl = "https://test.alhelp.net/stage-api/"
// const baseUrl ="https://info.alhelp.net/prod-api/"
// const baseUrl ="http://192.168.85.187:8080"

import AES from '@/utils/AES';
//带Token请求
const Request = (data) => {
	let token = "";
	token = uni.getStorageSync('token') ? 'Bearer ' + uni.getStorageSync('token') : ''

	//此token是登录成功后后台返回保存在storage中的
	let DefaultOpts = {
		url: baseUrl + data.url,
		data: data.data,
		method: data.method,
		header: {
			'Authorization': token,
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8",
			"SystemType": 1,
			"AppName": "BKZS",
			"AppType": "WECHAT_MINI"
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(DefaultOpts).then(
			(res) => {
				let encryptUrl = (data.url.indexOf('/data-core/') != -1) ? true : false
				let decryptData = ''
				if (encryptUrl && res[1].data.data) {
					decryptData = JSON.parse(AES.decrypt(res[1].data.data))
				} else {
					decryptData = res[1].data
				}
				//当code码为100000（成功）和 500000（免费次数用完，pc端接口需要这个判断）时，均返回
				if (decryptData.code == 100000 || decryptData.code == 500000) {
					// 后端返回的状态码100000为成功状态,成功则返回请求结果
					resolve(decryptData)
				} else if (decryptData.code == 900002) {
					// 后端返回状态码为900002则为登录过期或未登录状态（以项目实际情况为准）
					if (uni.getStorageSync('navigateLogin')) return;
					uni.showToast({
						icon: 'none',
						title: '您未登录，请先登录',
						duration: 2000
					});
					uni.clearStorageSync()
					let pages = getCurrentPages()
					// 存路径是用来判断跳转登录前在哪个页面，登录后跳转回去
					uni.setStorageSync('prePath', pages[pages.length - 1].$page.fullPath)
					// 仍然保留获取到的手机信息,手机品牌
					uni.setStorageSync('systemInfo', uni.getSystemInfoSync())
					uni.setStorageSync('brand', uni.getDeviceInfo().deviceBrand)
					uni.setStorageSync('navigateLogin', true)
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login'
						})
					}, 2000)

				} else {
					uni.showToast({
						icon: 'none',
						title: decryptData.msg || '请求失败',
						duration: 2000
					});
					setTimeout(() => {
						resolve(decryptData)
					}, 2000)
				}
			}
		).catch(
			(err) => {
				uni.showToast({
					icon: 'none',
					title: "不好意思，我可能出了点问题！",
					duration: 3000
				})
				reject(err)
			}
		)
	})
	return promise
}
export default {
	baseUrl,
	Request
}